<template>
	<view class="container">
		<!-- 宠物选择器 -->
		<view class="pet-selector">
			<picker 
				:value="selectedPetIndex" 
				:range="pets" 
				range-key="name"
				@change="onPetChange"
				class="pet-picker"
			>
				<view class="picker-content">
					<image 
						:src="selectedPet.photo || '/static/img/default-pet.png'" 
						class="pet-avatar"
						mode="aspectFill"
					></image>
					<text class="pet-name">{{selectedPet.name || '选择宠物'}}</text>
					<text class="picker-arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 实时位置卡片 -->
		<view class="location-card" v-if="currentLocation">
			<view class="card-header">
				<text class="card-title">实时位置</text>
				<text class="location-time">{{formatDateTime(currentLocation.locationTime)}}</text>
			</view>
			<view class="location-info">
				<view class="location-coords">
					<text class="coord-label">经度:</text>
					<text class="coord-value">{{currentLocation.longitude}}</text>
				</view>
				<view class="location-coords">
					<text class="coord-label">纬度:</text>
					<text class="coord-value">{{currentLocation.latitude}}</text>
				</view>
				<view class="location-address" v-if="currentLocation.address">
					<text class="address-label">地址:</text>
					<text class="address-value">{{currentLocation.address}}</text>
				</view>
			</view>
		</view>
		
		<!-- 地图容器 -->
		<view class="map-container">
			<map 
				:latitude="mapCenter.latitude" 
				:longitude="mapCenter.longitude"
				:markers="markers"
				:polyline="polyline"
				:scale="15"
				:show-location="true"
				class="map"
				@markertap="onMarkerTap"
			></map>
		</view>
		
		<!-- 轨迹控制 -->
		<view class="track-controls">
			<view class="control-row">
				<button 
					class="control-btn" 
					:class="{ active: showTrack }"
					@click="toggleTrack"
				>
					{{showTrack ? '隐藏轨迹' : '显示轨迹'}}
				</button>
				<button 
					class="control-btn" 
					@click="refreshLocation"
				>
					刷新位置
				</button>
			</view>
			<view class="control-row">
				<button 
					class="control-btn" 
					@click="setFence"
				>
					设置围栏
				</button>
				<button 
					class="control-btn" 
					@click="viewHistory"
				>
					历史轨迹
				</button>
			</view>
		</view>
		
		<!-- 统计信息 -->
		<view class="stats-section">
			<view class="stat-item">
				<text class="stat-number">{{todayPoints}}</text>
				<text class="stat-label">今日定位点</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{totalDistance}}</text>
				<text class="stat-label">总距离(km)</text>
			</view>
			<view class="stat-item">
				<text class="stat-number">{{avgSpeed}}</text>
				<text class="stat-label">平均速度</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			pets: [],
			selectedPetIndex: 0,
			selectedPet: {},
			currentLocation: null,
			locationHistory: [],
			showTrack: false,
			mapCenter: {
				latitude: 39.9042,
				longitude: 116.4074
			},
			markers: [],
			polyline: [],
			baseUrl: 'http://localhost:8080/dev-api/api'
		}
	},
	computed: {
		todayPoints() {
			return this.locationHistory.filter(loc => {
				const today = new Date().toDateString()
				return new Date(loc.locationTime).toDateString() === today
			}).length
		},
		totalDistance() {
			// 简单的距离计算，实际项目中需要更精确的算法
			return (this.locationHistory.length * 0.1).toFixed(1)
		},
		avgSpeed() {
			return '2.5 km/h'
		}
	},
	onLoad() {
		this.loadPets()
		this.startLocationTracking()
	},
	methods: {
		async loadPets() {
			try {
				const response = await uni.request({
					url: `${this.baseUrl}/pets/user/1`,
					method: 'GET'
				})
				
				if (response.statusCode === 200) {
					this.pets = response.data
					if (this.pets.length > 0) {
						this.selectedPet = this.pets[0]
						this.loadLocationHistory()
					}
				}
			} catch (error) {
	
			}
		},
		
		onPetChange(e) {
			this.selectedPetIndex = e.detail.value
			this.selectedPet = this.pets[this.selectedPetIndex]
			this.loadLocationHistory()
		},
		
		async loadLocationHistory() {
			if (!this.selectedPet.id) return
			
			try {
				const response = await uni.request({
					url: `${this.baseUrl}/location/pet/${this.selectedPet.id}`,
					method: 'GET'
				})
				
				if (response.statusCode === 200) {
					this.locationHistory = response.data
					this.updateMapMarkers()
					if (this.locationHistory.length > 0) {
						this.currentLocation = this.locationHistory[0]
						this.updateMapCenter()
					}
				}
			} catch (error) {

			}
		},
		
		updateMapMarkers() {
			this.markers = this.locationHistory.map((location, index) => ({
				id: index,
				latitude: location.latitude,
				longitude: location.longitude,
				title: `${this.selectedPet.name} - ${this.formatDateTime(location.locationTime)}`,
				iconPath: index === 0 ? '/static/img/marker-current.png' : '/static/img/marker-history.png',
				width: 30,
				height: 30
			}))
		},
		
		updateMapCenter() {
			if (this.currentLocation) {
				this.mapCenter = {
					latitude: this.currentLocation.latitude,
					longitude: this.currentLocation.longitude
				}
			}
		},
		
		toggleTrack() {
			this.showTrack = !this.showTrack
			if (this.showTrack) {
				this.updatePolyline()
			} else {
				this.polyline = []
			}
		},
		
		updatePolyline() {
			if (this.locationHistory.length > 1) {
				this.polyline = [{
					points: this.locationHistory.map(location => ({
						latitude: location.latitude,
						longitude: location.longitude
					})),
					color: '#007AFF',
					width: 3,
					arrowLine: true
				}]
			}
		},
		
		async refreshLocation() {
			uni.showLoading({
				title: '获取位置中...'
			})
			
			// 模拟获取新位置
			setTimeout(() => {
				uni.hideLoading()
				this.loadLocationHistory()
			}, 2000)
		},
		
		setFence() {
			uni.navigateTo({
				url: '/pages/location/fence'
			})
		},
		
		viewHistory() {
			uni.navigateTo({
				url: `/pages/location/history?petId=${this.selectedPet.id}`
			})
		},
		
		onMarkerTap(e) {
			const marker = this.markers[e.markerId]
			uni.showToast({
				title: marker.title,
				icon: 'none'
			})
		},
		
		startLocationTracking() {
			// 模拟实时定位更新
			setInterval(() => {
				if (this.selectedPet.id) {
					this.loadLocationHistory()
				}
			}, 30000) // 每30秒更新一次
		},
		
		formatDateTime(dateTime) {
			const date = new Date(dateTime)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.pet-selector {
	background: white;
	padding: 20rpx;
	margin-bottom: 20rpx;
}

.pet-picker {
	width: 100%;
}

.picker-content {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background: #f8f8f8;
	border-radius: 10rpx;
}

.pet-avatar {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.pet-name {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999;
}

.location-card {
	background: white;
	margin: 0 20rpx 20rpx;
	border-radius: 15rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.location-time {
	font-size: 24rpx;
	color: #999;
}

.location-info {
	display: flex;
	flex-direction: column;
	gap: 15rpx;
}

.location-coords {
	display: flex;
	align-items: center;
}

.coord-label {
	font-size: 26rpx;
	color: #666;
	width: 80rpx;
}

.coord-value {
	font-size: 26rpx;
	color: #333;
	font-weight: bold;
}

.location-address {
	display: flex;
	align-items: flex-start;
}

.address-label {
	font-size: 26rpx;
	color: #666;
	width: 80rpx;
}

.address-value {
	font-size: 26rpx;
	color: #333;
	flex: 1;
}

.map-container {
	margin: 0 20rpx 20rpx;
	border-radius: 15rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.map {
	width: 100%;
	height: 400rpx;
}

.track-controls {
	background: white;
	margin: 0 20rpx 20rpx;
	border-radius: 15rpx;
	padding: 30rpx;
}

.control-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.control-row:last-child {
	margin-bottom: 0;
}

.control-btn {
	flex: 1;
	margin: 0 10rpx;
	padding: 20rpx;
	background: #f0f0f0;
	color: #333;
	border: none;
	border-radius: 10rpx;
	font-size: 26rpx;
}

.control-btn.active {
	background: #007AFF;
	color: white;
}

.stats-section {
	display: flex;
	justify-content: space-between;
	margin: 0 20rpx 20rpx;
}

.stat-item {
	background: white;
	padding: 30rpx;
	border-radius: 15rpx;
	text-align: center;
	flex: 1;
	margin: 0 10rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.stat-number {
	font-size: 32rpx;
	font-weight: bold;
	color: #007AFF;
	display: block;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
	margin-top: 10rpx;
}
</style>